package com.ruoyi.project.tool.swagger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.channel.clientInfo.domain.ClientInfo;
import com.ruoyi.project.channel.clientInfo.service.IClientInfoService;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.channelOrder.service.IChannelOrderService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

/**
 * swagger 测试方法
 *
 * @author ruoyi
 */
@Api("通道信息管理")
@Controller
@RequestMapping("/channel/*")
public class ChannelController extends BaseController {
    @Autowired
    private IChannelOrderService channelOrderService;
    @Autowired
    private IClientInfoService clientInfoService;
    @Autowired
    private IChannelAccountService channelAccountService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    private String privateKey="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEA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5HYEeZbn9YERVr0HPrV2MWr8tvBMmrfSj3NBDTkA+KObf+uq47Uu5B3t04FCqitOQLXUISTngG1PKZWxcypUzsswOjghXX2AKBxNv6i/kxKtN0nFUBapuhgbcX4uvIiINv1ToEMDVkAAjgRbzOSQKBgQDJq740Ytp20Zb/vaAfml9E7CwLdiQV/B3r7uVSaSRDXaWIiMIjUeNqopRbp52z3PFLCGvs2SvoVqs85QMXwRdat/F8ikaGn9nKNvVrIWaZnibCTD6QbeDndGC6xvChobyS9WICeS8c+UJKWYjZs4mYpjpURNAbG/NKqKMogKUNcQKBgQCMmlaD/0wywC5rKNbSAVA0rbYS4pWvukso9LixfNnWS5XudCM4fFbSmQeuremQfJ5FxxyRlTVMHl9G8KnC4QoxTkE2urptpQLz0z/rjpPnVGHnNpROcP4gv602+7HXwW1ww45GXX4zGwXdOxfSl5kXiWr+0cnX8ygZeIs0zDVGxA==";
    private String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmOji8TA47cwgyr3sFjY7ZRrjJufyZSCluD5TFP1n2cADFl2mgPoYWjklDBWZ36Adu0QjHxVBGCoZt9Z2Pb/bwO2Cigi3Z+3IELJtpcPUSaiyGFGKwDjf5WmDIPeewr5vjrjkj/v8I3WF1Ny6jb/vO4PNmjKqGzplMANp+qM48m6AgJmEH5Nhv3go6WuertzDjH6bp4ko/i5W9HwjpK2MjQjq/LP0KaFs+lFSCo9eqOK7tnhMwiXwW/OG4HTUl93HdtlrxhMmsf6x5DOlxyRaUi+ayyIm/d2LNxowJEZHK4VRs+Y2YcG40bleSNV83tTenI82PvcNcBwatD1jal6DzQIDAQAB";
    @ApiOperation("更新通道订单")
    @PostMapping("update")
    @ResponseBody
    public AjaxResult update(ClientInfo clientInfo, String time, ModelMap mmap) {
        // 手机端成功后更新数据
        String key = "fdfdf#@zXCHP!b9OYFWWW&ViGBcYpLJCRW8nmsFRR";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("");
        stringBuilder.append(time);
        stringBuilder.append(key);
        Date date = new Date();
        date.setTime(Long.parseLong(time + "000"));
        clientInfo.setTime(date);
        clientInfo.setCreateTime(new Date());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return toAjax(1);
        }
        ChannelOrder channelOrder;
        try {
            String str = URLDecoder.decode(clientInfo.getData(), "utf-8");
            clientInfo.setData(str);
            JSONObject data = JSONObject.parseObject(str);
            clientInfo.setAmount(data.getBigDecimal("amount"));
            if (clientInfo.getAction().equals("rec_packet_info")) {
                clientInfo.setFromUid(data.getString("fromUId"));
                JSONObject tmp = JSONObject.parseObject(data.getString("templateData"));
                clientInfo.setOrderId(tmp.getString("m"));
            } else if (clientInfo.getAction().equals("transfer_accounts")) {
                clientInfo.setFromUid(data.getString("fromUId"));
                clientInfo.setOrderId(data.getString("orderId"));
            }
            ChannelOrder order = new ChannelOrder();
            order.setFromAlipayId(clientInfo.getFromUid());
            order.setAccount(clientInfo.getAccount());
            order.setAmount(clientInfo.getAmount());
            order.setOrderStatus("0"); // 搜索待支付的订单
            List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
            if (channelOrders.size() == 0) {
                AjaxResult result = toAjax(-1);
                result.setMsg("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号"+clientInfo.getAccount()+";交易金额"+clientInfo.getAmount()+"的工单号");
                clientInfo.setOrderStatus("1");
                clientInfoService.insertClientInfo(clientInfo);
                return result;
            }
            channelOrder = channelOrders.get(0);
            channelOrder.setOrderStatus("1");
            channelOrder.setPayAmount(clientInfo.getAmount());
            channelOrder.setSuccessTime(new Date());
            channelOrder.setUpdateTime(new Date());
            // 获取商户信息
            BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
            channelOrder.setBusinessFee(businessInfo.getChannelRate().multiply(channelOrder.getPayAmount()));



            channelOrderService.updateChannelOrder(channelOrder);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return toAjax(clientInfoService.insertClientInfo(clientInfo));
    }

    /**
     * 用来做测试的
     *
     * @param channelOrder
     * @param mmap
     * @return
     */
    @ApiOperation("新增通道订单")
    @GetMapping("addChannelOrder")
    public String savetest(ChannelOrder channelOrder, ModelMap mmap) {
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&amount=").append(channelOrder.getAmount());
        stringBuilder.append("&serverUrl=").append(channelOrder.getServerUrl());
        stringBuilder.append("&returnUrl=").append(channelOrder.getReturnUrl());

        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        channelOrder.setChannelUserId(businessInfo.getChannelUserId());
        ChannelOrder serchOrder = new ChannelOrder();
        serchOrder.setChildOrderno(channelOrder.getChildOrderno());
        serchOrder.setBusinessId(channelOrder.getBusinessId());
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(serchOrder);
        AjaxResult result;
        if (channelOrders.size() > 0) {
            channelOrder = channelOrders.get(0);
            result = toAjax(1);
        } else {
            channelOrder.setOrderStatus("0");
            channelOrder.setCreateTime(new Date());
            channelOrder.setStatus("0");
            channelOrder.setCreateBy(channelOrder.getBusinessId() + "");
            channelOrder.setChannelUserId(businessInfo.getChannelUserId());
            result = toAjax(channelOrderService.insertChannelOrder(channelOrder));
        }
        result.setData(channelOrder);
        mmap.put("channelOrder", channelOrder);
        if (channelOrder.getSuccessTime() != null) {
            mmap.put("qrcode", "success");
        } else {
            //https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2019051064475084&scope=auth_base&redirect_uri=ENCODED_URL
//            String uri = "http://192.168.43.11/channel/alipay?orderId=" + channelOrder.getOrderId();
            String uri = "http://gapilan.cn/channel/alipay?orderId=" + channelOrder.getOrderId();
            try {
                uri = URLEncoder.encode(uri, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            mmap.put("qrcode", "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2019051064475084&scope=auth_base&redirect_uri=" + uri);
            //   mmap.put("qrcode", "http://192.168.43.11/channel/alipay?orderId=" + channelOrder.getOrderId());
//            mmap.put("qrcode", "http://gapilan.cn/channel/alipay?orderId=" + channelOrder.getOrderId());
        }
//        mmap.put("qrcode", "http://gapilan.cn/channel/alipay?orderId=" + channelOrder.getOrderId());
        return "openAlipay";
    }

    /**
     * 用来做测试的, 这个接口是用户已经通过支付宝扫码了,才能看到的页面
     *
     * @param orderId
     * @param mmap
     * @return
     */
    @ApiOperation("打开支付页面")
    @GetMapping("alipay")
    public String alipay(String orderId, String auth_code, ModelMap mmap) {
        //
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2019051064475084", privateKey, "json", "UTF-8", publicKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(auth_code);
        request.setGrantType("authorization_code");
        String userId="" ;
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            // 付款方userid
            userId = oauthTokenResponse.getUserId();
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
        }
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        // 打开支付页面后再轮询账号
        ChannelAccount searchAcc = new ChannelAccount();
        searchAcc.setStatus("0");
        searchAcc.setChannelUserId(channelOrder.getChannelUserId());
        List<ChannelAccount> channelAccounts = channelAccountService.selectChannelAccountList(searchAcc);
        Random ra = new Random();
        ChannelAccount account = channelAccounts.get(ra.nextInt(channelAccounts.size()));
        channelOrder.setFromAlipayId(userId);
        channelOrder.setAccount(account.getAccount());
        channelOrderService.updateChannelOrder(channelOrder);
        mmap.put("channelOrder", channelOrder);
        mmap.put("account", account);
        String type = "alipay";
        if (channelOrder.getPayType().equals("1")) {
            // 红包
            type = "alipay/redpay";
        }else if (channelOrder.getPayType().equals("5")) {
            // 转账
            type = "alipay/newredpay";
        }else if (channelOrder.getPayType().equals("2")) {
            // 转账
            type = "alipay/costs";
        }
        return type;
    }

    @ApiOperation("获取列表")
    @GetMapping("list")
    @ResponseBody
    public AjaxResult channelList() {
        ChannelOrder channelOrder = new ChannelOrder();
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        return AjaxResult.success("success", list);
    }

    @ApiOperation("获取订单状态")
    @GetMapping("orderStatus/{orderId}")
    @ResponseBody
    public AjaxResult getOrderStatus(@PathVariable("orderId") String orderId) {
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        return AjaxResult.success("操作成功", channelOrder);
    }

    @GetMapping("test")
    public String test() {
        return "test";
    }



    @GetMapping("alipayAuth")
    public String alipayAuth() {
        try {
            URLEncoder.encode("中国", "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return " https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2019051064475084&scope=auth_base&redirect_uri=ENCODED_URL";
    }

    @PostMapping("callback")
    @ResponseBody
    public AjaxResult callback(@RequestBody ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(Long.valueOf(14));
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&payAmount=").append(channelOrder.getPayAmount());
        stringBuilder.append("&orderStatus=").append(channelOrder.getOrderStatus());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());

        // 编号14专门用来测试,不需要鉴权
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }

        return AjaxResult.success("鉴权成功");
    }

    // https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=APPID&scope=SCOPE&redirect_uri=ENCODED_URL
	/*
    private final static List<Test> testList = new ArrayList<>();
    {
        testList.add(new Test("1", "admin", "admin123"));
        testList.add(new Test("2", "ry", "admin123"));
    }





    @ApiOperation("更新用户")
    @ApiImplicitParam(name = "Test", value = "单个用户信息", dataType = "Test")
    @PutMapping("update")
    public AjaxResult update(Test test)
    {
        return testList.remove(test) && testList.add(test) ? success() : error();
    }

    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "Tests", value = "单个用户信息", dataType = "Test")
    @DeleteMapping("delete")
    public AjaxResult delete(Test test)
    {
        return testList.remove(test) ? success() : error();
    }
    */
}


